﻿//************************************************************************************************
// Copyright © 2014 Steven M. Cohn. All Rights Reserved.
// 
//************************************************************************************************

namespace River.Folderize
{
	using System;
	using System.IO;
	using System.Management;


	/// <summary>
	/// Some fundamental file system operations.
	/// </summary>
	
	internal static class PathHelper
	{

		/// <summary>
		/// Removes the read-only flat from the specified file.
		/// </summary>
		/// <param name="path">The path to the file to make writable.</param>
		/// <returns>A Boolean value indicating whether the operation succeeded.</returns>

		public static bool EnsureWritable (string path)
		{
			if (File.Exists(path))
			{
				try
				{
					var attributes = File.GetAttributes(path);
					if ((attributes & FileAttributes.ReadOnly) > 0)
					{
						attributes &= ~FileAttributes.ReadOnly;
						File.SetAttributes(path, attributes);
					}
				}
				catch
				{
					return false;
				}
			}

			return true;
		}


		/// <summary>
		/// Converts a UNC path to a local path by discovering the path
		/// shared by the machine in the UNC path.
		/// </summary>
		/// <param name="unc">A UNC path.</param>
		/// <returns>A local path.</returns>

		public static string GetLocalPath (string unc)
		{
			unc = unc.Trim();
			if (!unc.StartsWith(@"\\"))
			{
				return Path.GetFullPath(unc);
			}

			// strip off the leading "\\" from the UNC path
			unc = unc.Substring(2);

			var parts = unc.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
			if (parts.Length < 2)
			{
				return null;
			}

			string path = null;

			try
			{
				// connect to the server (hopefully local machine name)
				var scope = new ManagementScope(@"\\" + parts[0] + @"\root\cimv2");
				// query the server for the share name
				var query = new SelectQuery("select * from Win32_Share where Name='" + parts[1] + "'");

				using (var searcher = new ManagementObjectSearcher(scope, query))
				{
					// Get the path
					foreach (ManagementObject mob in searcher.Get())
					{
						path = mob["path"].ToString();
					}
				}
			}
			catch
			{
				return null;
			}

			// append remaining folders to the local path name
			if (parts.Length > 2)
			{
				for (int i = 2; i < parts.Length; i++)
				{
					path = Path.Combine(path, parts[i]);
				}
			}

			return path;
		}
	}
}
